<script setup lang="ts">
import {
  addPatient,
  getPatientList as getPatientListAPI,
  editPatient,
  delPatient
} from '@/services/user'
import type { Patient } from '@/types/user'
import type { PatientList } from '@/types/user'
import {
  showConfirmDialog,
  showFailToast,
  showSuccessToast,
  showToast
} from 'vant'
import { computed } from 'vue'
import { ref } from 'vue'
import IDValidator from 'id-validator'
import { useRoute } from 'vue-router'
import { useConsultStore } from '@/stores'
import { useRouter } from 'vue-router'
const validator = new IDValidator()

const patientList = ref<PatientList>([])

const getPatientList = async () => {
  const r = await getPatientListAPI()
  patientList.value = r.data

  // 默认选中
  // 是选择患者页面，并且具有患者列表
  if (isChange.value && patientList.value.length > 0) {
    // 优先选中默认的
    const defPatient = patientList.value.find((item) => item.defaultFlag === 1)
    if (defPatient) {
      patientId.value = defPatient.id
    } else {
      // 如果没有默认的患者，就选中第 0 项
      patientId.value = patientList.value[0].id
    }
  }
}
getPatientList()

const options = [
  { label: '男', value: 1 },
  { label: '女', value: 0 }
]
// const gender = ref<number | string>(1)

// 控制添加患者的弹框的变量
const show = ref(false)
const showPopup = (item?: Patient) => {
  if (item) {
    // 回填
    const { id, name, idCard, gender, defaultFlag } = item
    patient.value = {
      id,
      name,
      idCard,
      gender,
      defaultFlag
    }
  } else {
    // lodash.cloneDeep
    patient.value = { ...initPatient }
    // 下面写法，当输入的时候，会影响 patient.value，间接影响到了 initPatient
    // patient.value = initPatient
  }
  show.value = true
}

const initPatient: Patient = {
  name: '',
  idCard: '',
  defaultFlag: 0, // 1 表示默认的
  gender: 1 // 1 表示男
}

// const patient = ref<Patient>({} as Patient)
const patient = ref<Patient>({ ...initPatient })

// 单独处理 defaultFlag，组件需要的是 true、false；后端需要的是 1、0
const defaultFlag = computed({
  get() {
    // return patient.value.defaultFlag === 0 ? false : true
    return !!patient.value.defaultFlag
  },
  set(newValue) {
    // 根据收集到的 true false 来改变 patient.value.defaultFlag
    // patient.value.defaultFlag = newValue === true ? 1 : 0
    patient.value.defaultFlag = newValue ? 1 : 0
    /* if(flag) {
      oBar.style = true
    } else {
      oBar.style = false
    }
    oBar.style = !!flag */
  }
})

const submit = async () => {
  // 非空校验
  if (!patient.value.name) return showFailToast('请输入真实姓名')
  if (!patient.value.idCard) return showFailToast('请输入身份证号')
  // 身份证校验
  const isValid = validator.isValid(patient.value.idCard)
  if (!isValid) return showFailToast('身份证校验失败')
  const { sex } = validator.getInfo(patient.value.idCard)
  if (sex !== patient.value.gender)
    return showFailToast('身份证和输入的性别不一致')

  await (patient.value.id
    ? editPatient(patient.value)
    : addPatient(patient.value))

  show.value = false
  getPatientList()
  showSuccessToast(patient.value.id ? '编辑' : '添加' + '患者成功')
}

const delUser = async () => {
  await showConfirmDialog({
    title: '温馨提示',
    message: `您确认要删除 ${patient.value.name} 患者信息吗 ？`,
    cancelButtonText: '取消',
    confirmButtonText: '确认'
  })
  // await delPatient(patient.value.id as string)
  await delPatient(patient.value.id!)
  getPatientList()
  show.value = false
  showSuccessToast('删除成功')
}

// 兼容逻辑
// #1 获取 isChange 的值
const route = useRoute()
const isChange = computed(() => {
  return route.query.isChange === '1'
})
// #2 根据 isChange true or false 处理标题，处理文案提示，处理下一步按钮的显示与否

const patientId = ref<string>()
const selectedPatient = (item: Patient) => {
  if (isChange.value) {
    patientId.value = item.id
  }
}

const consultStore = useConsultStore()
const router = useRouter()

const next = () => {
  if (!patientId.value) return showToast('请选就诊择患者')
  // 记录选择的 patientId 到 Pinia
  consultStore.setPatient(patientId.value)
  // 跳转到支付页面
  router.push('/consult/pay')
}
</script>

<template>
  <div class="patient-page">
    <cp-nav-bar :title="isChange ? '选择患者' : '家庭档案'"></cp-nav-bar>
    <!-- 如果是选择患者显示【头部提示】 -->
    <div class="patient-change" v-if="isChange">
      <h3>请选择患者信息</h3>
      <p>以便医生给出更准确的治疗，信息仅医生可见</p>
    </div>
    <div class="patient-list">
      <div
        class="patient-item"
        v-for="item in patientList"
        :key="item.id"
        @click="selectedPatient(item)"
        :class="{ selected: patientId === item.id }"
      >
        <div class="info">
          <span class="name">{{ item.name }}</span>
          <!-- 每一个括号表示一个分组，$1 就可以第一个分组 -->
          <!-- <span class="id">{{
            item.idCard.replace(/(\d{3})\d{11}(\d{4})/, '$1***********$2')
          }}</span> -->
          <!-- ?: 表示不参与分组的计算 -->
          <span class="id">{{
            item.idCard.replace(/(\d{3})(?:\d+)(\d{4})/, '$1***********$2')
          }}</span>
          <span>{{ item.genderValue }}</span>
          <span>{{ item.age }} 岁</span>
        </div>
        <div class="icon">
          <cp-icon name="user-edit" @click="showPopup(item)" />
        </div>
        <div class="tag" v-if="item.defaultFlag === 1">默认</div>
      </div>
      <div
        class="patient-add"
        v-if="patientList.length < 6"
        @click="showPopup()"
      >
        <cp-icon name="user-add" />
        <p>添加患者</p>
      </div>
      <div class="patient-tip">最多可添加 6 人</div>
    </div>
    <!-- 如果是选择患者显示【底部按钮】 -->
    <div class="patient-next" v-if="isChange">
      <van-button type="primary" round block @click="next">下一步</van-button>
    </div>
    <!-- 添加患者的弹框 -->
    <van-popup v-model:show="show" position="right">
      <cp-nav-bar
        :back="() => (show = false)"
        :title="patient.id ? '编辑患者' : '添加患者'"
        right-text="保存"
        @clickRight="submit"
      ></cp-nav-bar>
      <van-form autocomplete="off">
        <van-field
          label="真实姓名"
          v-model="patient.name"
          placeholder="请输入真实姓名"
        />
        <van-field
          label="身份证号"
          v-model="patient.idCard"
          placeholder="请输入身份证号"
        />
        <van-field label="性别">
          <!-- 单选按钮组件 -->
          <template #input>
            <cp-radio-btn
              :options="options"
              v-model="patient.gender"
            ></cp-radio-btn>
          </template>
        </van-field>
        <van-field label="默认就诊人">
          <template #input>
            <van-checkbox round v-model="defaultFlag" />
          </template>
        </van-field>
      </van-form>
      <!-- 编辑状态才需要展示删除按钮 -->
      <van-action-bar v-if="patient.id">
        <van-action-bar-button @click="delUser">删除</van-action-bar-button>
      </van-action-bar>
    </van-popup>
  </div>
</template>

<style lang="scss" scoped>
.patient-page {
  padding: 46px 0 80px;
  ::v-deep() {
    .van-popup {
      width: 100%;
      height: 100%;
      padding-top: 46px;
      box-sizing: border-box;
    }
  }
}
// 底部操作栏
.van-action-bar {
  padding: 0 10px;
  margin-bottom: 10px;
  .van-button {
    color: var(--cp-price);
    background-color: var(--cp-bg);
  }
}
.patient-list {
  padding: 15px;
}

.patient-item {
  display: flex;
  align-items: center;
  padding: 15px;
  background-color: var(--cp-bg);
  border-radius: 8px;
  margin-bottom: 15px;
  position: relative;
  border: 1px solid var(--cp-bg);
  transition: all 0.3s;
  overflow: hidden;

  .info {
    display: flex;
    flex-wrap: wrap;
    flex: 1;

    span {
      color: var(--cp-tip);
      margin-right: 20px;
      line-height: 30px;

      &.name {
        font-size: 16px;
        color: var(--cp-text1);
        width: 80px;
        margin-right: 0;
      }

      &.id {
        color: var(--cp-text2);
        width: 180px;
      }
    }
  }

  .icon {
    color: var(--cp-tag);
    width: 20px;
    text-align: center;
  }

  .tag {
    position: absolute;
    right: 60px;
    top: 21px;
    width: 30px;
    height: 16px;
    font-size: 10px;
    color: #fff;
    background-color: var(--cp-primary);
    border-radius: 2px;
    display: flex;
    justify-content: center;
    align-items: center;
  }

  &.selected {
    border-color: var(--cp-primary);
    background-color: var(--cp-plain);

    .icon {
      color: var(--cp-primary);
    }
  }
}

.patient-add {
  background-color: var(--cp-bg);
  color: var(--cp-primary);
  text-align: center;
  padding: 15px 0;
  border-radius: 8px;

  .cp-icon {
    font-size: 24px;
  }
}

.patient-tip {
  color: var(--cp-tag);
  padding: 12px 0;
}

.patient-change {
  padding: 15px;
  > h3 {
    font-weight: normal;
    margin-bottom: 5px;
  }
  > p {
    color: var(--cp-text3);
  }
}
.patient-next {
  padding: 15px;
  background-color: #fff;
  position: fixed;
  left: 0;
  bottom: 0;
  width: 100%;
  height: 80px;
  box-sizing: border-box;
}
</style>
